/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "arm_math.h"
#include "arm_common_tables.h"
#include "arm_const_structs.h"
#include "math.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define ssN 1024	//采样点数
#define listN 5
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define pi 3.1415926
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint32_t a,b,c,threshold=50,t_num=5;
uint32_t cnt = 0,cnt2 = 0;
uint32_t t11,t12,t13,mode=0;
float32_t an,distance;
float32_t anBuffer;
float32_t angleList[listN];
float32_t angleListMax;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void gss(uint32_t* ssource1,uint32_t* ssource2,uint32_t* ssource3);	//get sound source
float32_t uTOf(uint32_t n);			//type trans
void gyh(float32_t* f,uint32_t n);	//归一化guiyihua
void getT(uint32_t* t11, uint32_t* t12, uint32_t* t13);
void setServoDirect(float32_t Angle);
void sendAngle(float32_t angle,float32_t distance);
void start(void);
float32_t zhongweishu(float32_t* a, int size);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint16_t adcCpltFlag=1;

//float32_t ss1fft[ssN*2];	 	//信号�????????1
//float32_t ss2fft[ssN*2];	 	//信号�????????2
//float32_t ss3fft[ssN*2];	 	//信号�????????3
//float32_t ss1fft_cmplx[ssN*2];	 	//信号�????????1
//float32_t ss2fft_cmplx[ssN*2];	 	//信号�????????2
//float32_t ss3fft_cmplx[ssN*2];	 	//信号�????????1
//
//float32_t buffer1[ssN*2];	 	//�?????1
//float32_t buffer1[ssN*2];	 	//�?????2
//
//float32_t sssShow1;	 	//信号�????????1
//float32_t sssShow2; 	//信号�????????2
//float32_t sssShow3;	 	//信号�????????3

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_ADC3_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3);
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_4);
  HAL_GPIO_WritePin(GPIOG, GPIO_PIN_13, GPIO_PIN_SET);
  setServoDirect(90);
  an = 90;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14, GPIO_PIN_RESET);
	  getT(&a, &b, &c);
	  while(1)
	  {
		  mode = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
		  if(mode){
			  if(cnt == listN){
				  an = zhongweishu(angleList, listN);
				  setServoDirect(an);
				  sendAngle(an, distance);
				  cnt = 0;
				  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_SET);
				  HAL_Delay(2000);
				  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_RESET);

			  }
			  start();
			  angleList[cnt] = an;
			  cnt +=1;
		  }else{
			  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_SET);
			  anBuffer = an;
			  start();
//			  while(1)
//			  {
//				  if(abs(an-anBuffer)>20)
//				  {
//					  cnt2++;
//				  }
//				  if(cnt2 == 3)
//				  {
//					  anBuffer = an;
//				  }
				  setServoDirect(an);
				  sendAngle(an, distance);

//			  }
		  }
//		  setServoDirect(an);
//		  sendAngle(an,distance);
	  }
///////////////////////////////////////////////////////////////////////////////////////
	  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_SET);
//	  HAL_Delay(1000);
	  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_RESET);
	  HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14, GPIO_PIN_SET);

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 180;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Activate the Over-Drive mode
  */
  if (HAL_PWREx_EnableOverDrive() != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
	if(hadc==&hadc3)
	{
		adcCpltFlag=0;
	}
}

void getT(uint32_t* t11, uint32_t* t12, uint32_t* t13)
{

	uint32_t ssource1[ssN];	 	//信号�????????1
	uint32_t ssource2[ssN];	 	//信号�????????2
	uint32_t ssource3[ssN];	 	//信号�????????3
	float32_t ss1c[ssN];	 	//信号�????????1
	float32_t ss2c[ssN];	 	//信号�????????2
	float32_t ss3c[ssN];	 	//信号�????????3
	float32_t ss11corr[ssN*2-1];	 	//信号�????????1
	float32_t ss12corr[ssN*2-1];	 	//信号�????????2
	float32_t ss13corr[ssN*2-1];	 	//信号�????????3
	float32_t buffer;

	  gss(ssource1, ssource2, ssource3);
	  for(int i=0;i<ssN;i++)
	  {
		  ss1c[i]=uTOf(ssource1[i]);
		  ss2c[i]=uTOf(ssource2[i]);
		  ss3c[i]=uTOf(ssource3[i]);
	  }
	  //Tran sform uint32_t To float32_t

	  for(int i=1; i<ssN-1;i++)
	  {
		  ss1c[i]=(ss1c[i-1]+ss1c[i]+ss1c[i+1])/3;
		  ss2c[i]=(ss2c[i-1]+ss2c[i]+ss2c[i+1])/3;
		  ss3c[i]=(ss3c[i-1]+ss3c[i]+ss3c[i+1])/3;
	  }
	  //Sliding mean filtering

	  gyh(ss1c, ssN);
	  gyh(ss2c, ssN);
	  gyh(ss3c, ssN);
	  //normalization

	  for(int i=1; i<ssN-1;i++)
	  {
		  float32_t mean1,mean2,mean3;
		  arm_mean_f32(ss1c, ssN, &mean1);
		  arm_mean_f32(ss2c, ssN, &mean2);
		  arm_mean_f32(ss3c, ssN, &mean3);
		  ss1c[i]=ss1c[i]-mean1;
		  ss2c[i]=ss2c[i]-mean2;
		  ss3c[i]=ss3c[i]-mean3;
	  }
	  //remove mean

	  arm_correlate_f32(ss1c, ssN, ss1c, ssN, ss11corr);
	  arm_max_f32(ss11corr, ssN*2-1, &buffer, t11);

	  arm_correlate_f32(ss1c, ssN, ss2c, ssN, ss12corr);
	  arm_max_f32(ss12corr, ssN*2-1, &buffer, t12);

	  arm_correlate_f32(ss1c, ssN, ss3c, ssN, ss13corr);
	  arm_max_f32(ss13corr, ssN*2-1, &buffer, t13);
	  //get the time delayed
}
/*
 * @param ssource1
 * @param ssource2
 * @param ssource3
 * */
void gss(uint32_t* ssource1,uint32_t* ssource2,uint32_t* ssource3)
{
	HAL_ADC_Start_DMA(&hadc1, ssource1, ssN);
	HAL_ADC_Start_DMA(&hadc2, ssource2, ssN);
	HAL_ADC_Start_DMA(&hadc3, ssource3, ssN);
	HAL_TIM_Base_Start(&htim2);
	while(adcCpltFlag)
	{
		HAL_Delay(1);
	}
	adcCpltFlag=1;
	HAL_TIM_Base_Stop(&htim2);
}
/*
 * @param f
 * @param n
 * */
void gyh(float32_t* f,uint32_t n)
{
	uint32_t index;
	float min,max;
	arm_min_f32(f, n, &min, &index);
	for(int i=0;i<n;i++)
	{
		f[i] = f[i]-min;
	}
	arm_max_f32(f, n, &max, &index);
	for(int i=0;i<n;i++)
	{
		f[i] = f[i]*1000/max;
	}
}

float32_t uTOf(uint32_t n)
{
	float u;
	u = n/1.0;
	return u;
}
void setServoDirect(float32_t Angle)
{
	int i;
	Angle = Angle * 200+10000;
	i = (int)Angle;
	__HAL_TIM_SET_COMPARE(&htim3,TIM_CHANNEL_3, i);

}
void sendAngle(float32_t angle,float32_t distance)
{
	uint8_t asd[80]="                   ";
	sprintf(asd,"%f  %f",angle, distance);
	HAL_UART_Transmit(&huart1, asd, 80, 0xff);

}

void start(void)
{
	  getT(&a, &b, &c);
	 // a
	  t11 = a;
	  t12 = b;
	  t13 = c;
//	  if(t12 == 1028)
//		  an = 90;
	  if((800<t12)&&t12<1029)
	  {
		  an = -0.2046*((float)t12-1028)-0.01139;
		  distance = 275 / cos(an * pi / 180)+50*sin(an*pi/180);
		  an = 90 -an;

	  }

	  if(1028<t12&&t12<1200)
	  {
		  an = 0.2082*((float)t12-1028)-0.225;
		  distance = 275 / cos(an * pi / 180)+50*sin(an*pi/180);
		  an=90 +an;
	  }
	//test
}



float32_t zhongweishu(float32_t* a, int size)
{
	int i, j;
	float32_t mid,t;
	for (i = 0; i < size - 1; i++)//i为排序的趟数
	{
		for (j = 0; j < size - i - 1; j++)//j为第i趟需比较的次数
		{
			if (a[j] > a[j + 1])
			{
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t;
			}
		}
	}
	if (size % 2 == 0)//判断元素个数是否为偶数
	{
		mid = (a[size / 2] + a[size / 2 - 1]) / 2;
		printf("偶数的中位数是:%d\n", mid);
	}
	else
		mid = a[(size - 1) / 2];
	return mid;
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
